//
//  SpecialDetailViewController.m
//  WisdomZhuHai
//
//  Created by yewei on 14/10/27.
//  Copyright (c) 2014年 wyd. All rights reserved.
//

#import "SpecialDetailViewController.h"
#import "Common.h"
#import "AppDelegate.h"

@interface SpecialDetailViewController ()

@property (nonatomic,strong) NSArray *typeList;
@property (nonatomic,strong) NSMutableArray *viewControllers;   //标签对应的页面列表
@property (nonatomic,strong) NSMutableArray *specialDatas;      //所有咨询列表，每个元素也是一个数组
@property (nonatomic,strong) NSMutableArray *specialPageIndexs; //保存每个页面的当前游标,游标为当前数据的最后一条的下一条
@property (nonatomic,strong) NSString *currentTitle;            //当前标签标题
@property int topicId;
@end

@implementation SpecialDetailViewController

//const float TITLE_OFFSET = 9; //tab栏与上下的间距
const float PAGE_COUNT = 20;

-(id)initWithFrame:(CGRect)f typeList:(NSArray *)list topicId:(int)tId
{
    self = [super initWithFrame:f];
    if(self)
    {
        self.typeList = list;
        self.specialDatas = [NSMutableArray array];
        self.specialPageIndexs = [NSMutableArray array];
        self.topicId = tId;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];//[Common colorWithRGB:0xdbdcdc];
    [SVGloble shareInstance].globleWidth = self.view.bounds.size.width; //屏幕宽度
    [SVGloble shareInstance].globleHeight = self.view.bounds.size.height;
    [SVGloble shareInstance].globleTopHeight = 44;  //标签栏高度
    
    //获取第一个标签栏的数据
    if([self.typeList count] == 0)
    {
        return;
    }
    for(int i = 0; i < [self.typeList count]; ++i)
    {
        [self.specialDatas addObject:[NSNull null]];
        [self.specialPageIndexs addObject:[NSNumber numberWithInt:0]];
    }
    [self buildMainPage];
}

-(void)buildMainPage
{
    SVTopScrollView *topScrollView = [SVTopScrollView shareInstance];
    SVRootScrollView *rootScrollView = [SVRootScrollView shareInstance];
    NSMutableArray *names = [NSMutableArray array];
    for(NSDictionary *dic in self.typeList)
    {
        NSString *name = [Common valueForKey:P_VALUE dic:dic];
        [names addObject:name];
    }
    topScrollView.nameArray = names;
    topScrollView.backgroundColor = [UIColor whiteColor];
    topScrollView.svTopDelegate = self;
    rootScrollView.pageTitleArray = topScrollView.nameArray;
    rootScrollView.svrDelegate = self;
//    float y_ofset = TITLE_OFFSET; //tab栏与标题栏和列表的间距
//    CGRect f = topScrollView.frame;
//    f.origin.y = y_ofset;
//    topScrollView.frame = f;
//    f = rootScrollView.frame;
//    f.origin.y = 2*y_ofset + topScrollView.frame.size.height;
//    f.size.height = self.view.frame.size.height - topScrollView.frame.size.height - 2*y_ofset;
//    rootScrollView.frame = f;
  
    UIFont *font = [UIFont systemFontOfSize:14.0];
    topScrollView.labelFont = font;
    if (topScrollView.superview != self.view) {
        [topScrollView removeFromSuperview];
        [self.view addSubview:topScrollView];
    }
    if (rootScrollView.superview != self.view) {
        [rootScrollView removeFromSuperview];
        [self.view addSubview:rootScrollView];
    }
    
    self.viewControllers = [NSMutableArray array];
    for(int i = 0; i < [names count]; ++i)
    {
        SpecialDetailTableViewController *ctl = [[SpecialDetailTableViewController alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, rootScrollView.frame.size.height) style:UITableViewStylePlain];
        ctl.specialDelegate = self;
        ctl.nvControl = self.navigationController;
        [self.viewControllers addObject:ctl];
    }
    rootScrollView.viewControllerArray = self.viewControllers;
    [topScrollView initWithNameButtons];
    [rootScrollView initWithViewControllers];
    [rootScrollView refleshPageTitle];
    //[SVTopScrollView setSelectedIndex:0];
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

-(int)getIndexWithTypeId:(int)typeId
{
    for(int i=0; i<[self.typeList count]; ++i)
    {
        NSDictionary *item = [self.typeList objectAtIndex:i];
        int tId = [[Common valueForKey:P_ID dic:item] intValue];
        if(tId == typeId)
        {
            return i;
        }
    }
    return 0;
}
-(int)getIndexWithTypeName:(NSString *)typeName
{
    for(int i=0; i<[self.typeList count]; ++i)
    {
        NSDictionary *item = [self.typeList objectAtIndex:i];
        NSString * name = [Common valueForKey:P_VALUE dic:item];
        if([name isEqualToString:typeName])
        {
            return i;
        }
    }
    return 0;
}
-(void)didFinishGetMessageList:(NSDictionary *)dic
{
    if(dic == nil)
    {
        NSLog(@"specialDetail didFinishGetMessageList dic is nil");
        return;
    }
    NSString *typeId = [Common valueForKey:P_TYPEID dic:dic];
    int index = [self getIndexWithTypeId:[typeId intValue]];
    SpecialDetailTableViewController *table = [self.viewControllers objectAtIndex:index];
    [table resetPullTableViewState];
    NSArray *messageList = [Common valueForKey:P_V2_NEWS dic:dic];
    if([messageList count] == 0)
    {
        [table setEnableLoadMore:NO];
        return;
    }
    NSAssert(index < [self.specialDatas count], @"specialDetail didFinishGetMessageList index out of bounds");
    NSMutableArray *tempArray = nil;
    if([self.specialDatas objectAtIndex:index] == [NSNull null])
    {
        tempArray = [NSMutableArray arrayWithArray:messageList];
    }
    else
    {
        tempArray = [self.specialDatas objectAtIndex:index];
        [tempArray addObjectsFromArray:messageList];
    }
    [self.specialDatas replaceObjectAtIndex:index withObject:tempArray];
    //更新列表数据
    NSMutableArray *iconPaths = [NSMutableArray array];
    NSMutableArray *titles = [NSMutableArray array];
    NSMutableArray *subTitles = [NSMutableArray array];
    NSMutableArray *times = [NSMutableArray array];
    NSMutableArray *urls = [NSMutableArray array];
    for(int i = 0; i < [tempArray count]; ++i)
    {
        NSDictionary *rowDic = [tempArray objectAtIndex:i];
        [iconPaths addObject:[Common valueForKey:P_PHOTO dic:rowDic]];
        [titles addObject:[Common valueForKey:P_TITLE dic:rowDic]];
        [subTitles addObject:[Common valueForKey:P_SHORTCONTENT dic:rowDic]];
        [times addObject:[Common valueForKey:P_TIME dic:rowDic]];
        NSString *url = [NSString stringWithFormat:@"%@/%@/getContent?id=%d",[ProtocolManager shareInstance].api_base_url,APINEWSRELEASE,[[Common valueForKey:P_ID dic:rowDic] intValue]];
        [urls addObject:url];
    }
    table.iconPaths = iconPaths;
    table.titles = titles;
    table.subTitles = subTitles;
    table.times = times;
    table.urls = urls;
    if([messageList count] < PAGE_COUNT)
    {
        [table setEnableLoadMore:NO];
    }
    else
    {
        [table setEnableLoadMore:YES];
    }
    //更新游标
    int pageIndex = [tempArray count] + 1;
    [self.specialPageIndexs replaceObjectAtIndex:index withObject:[NSNumber numberWithInt:pageIndex]];
    [table.tableView reloadData];
    
}


#pragma mark - SVRootScrollViewDelegate
-(void)svRootScrollViewDidSelectPageWithTitle:(NSString *)title
{
    NSLog(@"svRootScrollViewDidSelectPageWithTitle:%@",title);
    self.currentTitle = title;
    //切换标签
    int index = [self getIndexWithTypeName:title];
    NSAssert(index < [self.specialDatas count], @"specialDetail svRootScrollViewDidSelectPageWithTitle index out of bounds!");
    if([self.specialDatas objectAtIndex:index] == [NSNull null])
    {
        //切换标签的时候，尚未加载数据的页面才加载数据
        NSDictionary *item = [self.typeList objectAtIndex:index];
        int typeId = [[Common valueForKey:P_ID dic:item] intValue];
        [[ProtocolManager shareInstance] getMessageList:typeId topicId:self.topicId returnCount:PAGE_COUNT beginNo:0 target:self selector:@selector(didFinishGetMessageList:)];
        
    }

}

#pragma SpecialDetailTableViewDelegate
-(void)specialDetailTableViewDidLoadMore:(SpecialDetailTableViewController *)specialDetailTableCtl
{
    //加载更多
    int index = [self getIndexWithTypeName:self.currentTitle];
    int pageIndex = [[self.specialPageIndexs objectAtIndex:index] intValue];
    NSDictionary *item = [self.typeList objectAtIndex:index];
    int typeId = [[Common valueForKey:P_ID dic:item] intValue];
    [[ProtocolManager shareInstance] getMessageList:typeId topicId:self.topicId returnCount:PAGE_COUNT beginNo:pageIndex target:self selector:@selector(didFinishGetMessageList:)];
}

-(void)specialDetailTableViewDidTriggerRefresh:(SpecialDetailTableViewController *)specialDetailTableCtl
{
    //下拉刷新
    int index = [self getIndexWithTypeName:self.currentTitle];
    [self.specialDatas replaceObjectAtIndex:index withObject:[NSNull null]];
    [self.specialPageIndexs replaceObjectAtIndex:index withObject:[NSNumber numberWithInt:0]];
    NSDictionary *item = [self.typeList objectAtIndex:index];
    int typeId = [[Common valueForKey:P_ID dic:item] intValue];
    [[ProtocolManager shareInstance] getMessageList:typeId topicId:self.topicId returnCount:PAGE_COUNT beginNo:0 target:self selector:@selector(didFinishGetMessageList:)];
    if([Common checkNetReachable])
    {
         SpecialDetailTableViewController *table = [self.viewControllers objectAtIndex:index];
        [table setPullRefreshDate:[NSDate date]];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
